//
//  LYouDetailController.m
//  LYouSubscribeApp
//
//  Created by grx on 2018/12/14.
//  Copyright © 2018年 grx. All rights reserved.
//

#import "LYouDetailController.h"
#import "GDNetServerDownLoadTool.h"
#import "LivePhotoMaker.h"
#import "LYSelectDownLoadView.h"
#import "LYouPreview.h"
#import "LYouBuyMemberController.h"
#import "LYShowCallController.h"
#import "GoogleMobileAds/GoogleMobileAds.h"

@interface LYouDetailController(){
  
}

@property (nonatomic,strong) NSURL *fileUrl;           /** 下载的url */
@property (nonatomic,strong) NSString *filePath;
@property (nonatomic,strong) NSURLSessionDownloadTask *task;
@property (nonatomic,assign) BOOL downLoadIng;
@property(nonatomic,strong) UIButton *backButton;
@property(nonatomic,strong) UIButton *previewButton;    /** 预览按钮 */
@property(nonatomic,strong) UIButton *collectionButton; /** 收藏按钮 */
@property(nonatomic,strong) UIButton *phoneShowButton;  /** 来电显示按钮 */
@property(nonatomic,strong) UIButton *downLoadButton;   /** 下载按钮 */
@property (nonatomic,strong) UIProgressView *progress;  /** 下载进度条 */
@property (nonatomic,strong) UILabel *tipsLable;  /** 下载提示语 */
@property (nonatomic,strong) LYSelectDownLoadView *downView;  /** 下载清晰度 */
@property (nonatomic,strong) LYouPreview *preview;  /** 预览 */
@property (nonatomic,strong) GADBannerView *adboadView;  /** 广告版位 */

@end

@implementation LYouDetailController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.detailVideoView resume];
    /** 查询是否收藏 */
    NSArray *allListArray = [[LYVideoInfoManager share]searchAllLocalVideoData];
    for (LYouVideoInfo *info in allListArray) {
        if ([info.videoId isEqualToString:self.model.post_id]) {
            /**此视频已收藏*/
            self.collectionButton.selected = YES;
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = ColorWithHexRGB(0x1F1E23);
    self.gk_navigationBar.hidden = YES;
    self.gk_statusBarHidden = YES;
    self.downLoadIng = NO;
//    self.model.video_url = @"http://www.apple.com/105/media/cn/iphone-x/2017/01df5b43-28e4-4848-bf20-490c34a926a7/films/feature/iphone-x-feature-cn-20170912_1280x720h.mp4";
    WeakSelf(weakSelf);
    /** 下载的文件目录 */
    NSString *localPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    self.filePath = [localPath  stringByAppendingPathComponent:@"LYouLivePhoto.mp4"];
    NSURL *path =  [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    self.fileUrl = [path URLByAppendingPathComponent:@"LYouLivePhoto.mp4"];
    
    /** 初始化播放器 */
    [self.view addSubview:self.detailVideoView];    
    /** 初始化播放按钮 */
    [self.view addSubview:self.playBtn];
    [self.playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    /** 初始化返回按钮 */
    [self.view addSubview:self.backButton];
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20);
        make.bottom.equalTo(self.view).offset(-50);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(35);
    }];
    /** 初始化预览按钮 */
    [self.view addSubview:self.previewButton];
    [self.previewButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.backButton).offset(50);
        make.bottom.equalTo(self.view).offset(-55);
        make.width.mas_equalTo(28);
        make.height.mas_equalTo(25);
    }];
    /** 初始化收藏按钮 */
    [self.view addSubview:self.collectionButton];
    [self.collectionButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.previewButton).offset(50);
        make.bottom.equalTo(self.view).offset(-52);
        make.width.mas_equalTo(28);
        make.height.mas_equalTo(28);
    }];
    /** 初始化来电显示按钮 */
    [self.view addSubview:self.phoneShowButton];
    [self.phoneShowButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.collectionButton).offset(50);
        make.bottom.equalTo(self.view).offset(-51);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(35);
    }];
    self.phoneShowButton.layer.cornerRadius = 35/2;
    /** 初始化下载按钮 */
    [self.view addSubview:self.downLoadButton];
    [self.downLoadButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-20);
        make.bottom.equalTo(self.view).offset(-48);
        make.width.mas_equalTo(35);
        make.height.mas_equalTo(35);
    }];
    /** 初始化进度条 */
    [self.view addSubview:self.progress];
    [self.progress mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(100);
        make.right.equalTo(self.view).offset(-100);
        make.centerY.equalTo(self.view);
    }];
    /** 初始化提示语 */
    [self.view addSubview:self.tipsLable];
    [self.tipsLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.right.equalTo(self.view).offset(0);
        make.centerY.equalTo(self.view).offset(20);
        make.height.mas_offset(30);
    }];
    if ([ISHAVEBUYMEMBER isEqualToString:@"no"]) {
        /** 插播广告 */
        [self.view addSubview:self.adboadView];
        self.adboadView.adUnitID = LYDetailADId;
        self.adboadView.rootViewController = self;
        [self.adboadView loadRequest:[GADRequest request]];
    }
    /** 初始化预览视图 */
    [self.view insertSubview:self.preview aboveSubview:self.detailVideoView];
    /** 初始化清晰度选择页面 */
    [self.view addSubview:self.downView];
    
    self.downView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 150);
    self.downView.closeBlock = ^{
        [UIView animateWithDuration:0.25
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseIn
                         animations:^ {
                             weakSelf.downView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 150);
                         }
                         completion:^(BOOL finished) {
                         }];
    };
    self.downView.downLoadBlock = ^(NSInteger tag){
        if (tag==11) {
            /** 下载高清视频 */
            /** 是否跳转到订购页面 */
            if ([ISHAVEBUYMEMBER isEqualToString:@"no"]) {
                /** 跳转到购买会员页 */
                LYouBuyMemberController *buyVC = [[LYouBuyMemberController alloc]init];
                [weakSelf.navigationController pushViewController:buyVC animated:YES];
                return;
            }
        }
        [UIView animateWithDuration:0.25
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseIn
                         animations:^ {
                             weakSelf.downView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 150);
                         }
                         completion:^(BOOL finished) {
                         }];
        /** 开始下载视频 */
        /** 删除视频 */
        [[GDNetServerDownLoadTool sharedTool]cancleLocalFile:weakSelf.filePath withUrlHost:weakSelf.model.video_url];
        weakSelf.progress.hidden = NO;
        weakSelf.tipsLable.hidden = NO;
        weakSelf.downLoadIng = YES;
        [weakSelf.downLoadButton setImage:[UIImage imageNamed:@"guanbi"] forState:UIControlStateNormal];
        NSURLSessionDownloadTask *tempTask = [[GDNetServerDownLoadTool sharedTool]AFDownLoadFileWithUrl:weakSelf.model.video_url progress:^(CGFloat progress) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.progress.progress = progress;
                NSLog(@"progress======%f",progress);
            });
        } fileLocalUrl:weakSelf.fileUrl filePath:weakSelf.filePath success:^(NSURL *fileUrlPath, NSURLResponse *response) {
            [weakSelf.downLoadButton setImage:[UIImage imageNamed:@"xiazai"] forState:UIControlStateNormal];
            weakSelf.downLoadIng = NO;
            NSLog(@"下载成功 下载的文档路径是 ====== %@, ",fileUrlPath);
            weakSelf.tipsLable.text = @"视频壁纸制作中";
            [weakSelf makeLivePhototoSave];
        } failure:^(NSError *error, NSInteger statusCode) {
            [weakSelf.downLoadButton setImage:[UIImage imageNamed:@"xiazai"] forState:UIControlStateNormal];
            weakSelf.downLoadIng = NO;
            NSLog(@"下载失败请检查网络!");
            
        }];
        weakSelf.task = tempTask;
    };
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(controlViewDidClick:)];
    [self.view addGestureRecognizer:tap];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.detailVideoView pause];
}

#pragma mark - 控制暂停播放
- (void)controlViewDidClick:(id)sender {
    if (self.detailVideoView.player.isPlaying) {
        [self.detailVideoView.player pausePlay];
        self.playBtn.hidden = NO;
    }else {
        [self.detailVideoView.player resumePlay];
        self.playBtn.hidden = YES;
    }
}

#pragma mark - 懒加载
- (LYouDetailVideoView *)detailVideoView {
    if (!_detailVideoView) {
        _detailVideoView = [[LYouDetailVideoView alloc]initWithVC:self videoModel:self.model];
    }
    return _detailVideoView;
}

- (UIButton *)playBtn {
    if (!_playBtn) {
        _playBtn = [UIButton new];
        [_playBtn setImage:[UIImage imageNamed:@"ss_icon_pause"] forState:UIControlStateNormal];
        [_playBtn addTarget:self action:@selector(playBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        _playBtn.hidden = YES;
    }
    return _playBtn;
}

- (UIButton *)previewButton {
    if (!_previewButton) {
        _previewButton = [UIButton new];
        [_previewButton setBackgroundImage:[UIImage imageNamed:@"Detailtupian"] forState:UIControlStateNormal];
        _previewButton.tag = 1000;
        [_previewButton addTarget:self action:@selector(previewButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _previewButton;
}

- (UIButton *)collectionButton {
    if (!_collectionButton) {
        _collectionButton = [UIButton new];
        [_collectionButton setBackgroundImage:[UIImage imageNamed:@"favorite"] forState:UIControlStateNormal];
        [_collectionButton setBackgroundImage:[UIImage imageNamed:@"favoriteSel"] forState:UIControlStateSelected];
        [_collectionButton addTarget:self action:@selector(collectionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _collectionButton;
}

- (UIButton *)phoneShowButton {
    if (!_phoneShowButton) {
        _phoneShowButton = [UIButton new];
        [_phoneShowButton setTitle:@"来电显示" forState:UIControlStateNormal];
        _phoneShowButton.titleLabel.font = LYFont_Medium(12);
        [_phoneShowButton setTitleColor:ColorWithHexRGB(0x00FF7F) forState:UIControlStateNormal];
        _phoneShowButton.layer.borderWidth = 2;
        _phoneShowButton.layer.borderColor = ColorWithHexRGB(0x00FF7F).CGColor;
        [_phoneShowButton addTarget:self action:@selector(phoneShowButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        /** 虚线 */
        if ([ISCheckIOS isEqualToString:@"yes"]) {
            _phoneShowButton.hidden = YES;
        }
    }
    return _phoneShowButton;
}

- (UIButton *)downLoadButton {
    if (!_downLoadButton) {
        _downLoadButton = [UIButton new];
        [_downLoadButton setImage:[UIImage imageNamed:@"xiazai"] forState:UIControlStateNormal];
        [_downLoadButton addTarget:self action:@selector(downLoadButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _downLoadButton;
}

-(UIProgressView *)progress {
    if (!_progress) {
        _progress = [UIProgressView new];
        //设置进度条的颜色
        _progress.trackTintColor=[UIColor lightGrayColor];
        _progress.progressTintColor = [UIColor whiteColor];
        //设置进度条的当前值，范围：0~1；
        _progress.progress = 0.0;
        _progress.layer.cornerRadius = 2.0;
        _progress.layer.masksToBounds = YES;
        _progress.progressViewStyle = UIProgressViewStyleDefault;
        _progress.transform = CGAffineTransformMakeScale(1.0f, 2.0f);
        _progress.hidden = YES;
    }
    return _progress;
}

- (UILabel *)tipsLable {
    if (!_tipsLable) {
        _tipsLable = [UILabel new];
        _tipsLable.text = @"正在下载视频";
        _tipsLable.textColor = [UIColor whiteColor];
        _tipsLable.textAlignment = NSTextAlignmentCenter;
        _tipsLable.font = LYFont_Medium(14);
        _tipsLable.hidden = YES;
    }
    return _tipsLable;
}

- (UIButton *)backButton {
    if (!_backButton) {
        _backButton = [UIButton new];
        [_backButton setImage:[UIImage imageNamed:@"jiantou_left"] forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}

-(LYSelectDownLoadView *)downView{
    if (!_downView) {
        _downView = [LYSelectDownLoadView new];
    }
    return _downView;
}

-(LYouPreview *)preview{
    if (!_preview) {
        _preview = [LYouPreview new];
        _preview.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        _preview.hidden = YES;
    }
    return _preview;
}
-(GADBannerView *)adboadView{
    if (!_adboadView) {
        _adboadView = [GADBannerView new];
        _adboadView.frame = CGRectMake(0, SCREEN_HEIGHT-48, SCREEN_WIDTH, 48);
    }
    return _adboadView;
}

-(void)playBtnClick:(UIButton *)sender{
    [self.detailVideoView.player resumePlay];
    self.playBtn.hidden = YES;
}

#pragma mark - 预览壁纸
-(void)previewButtonClick:(UIButton *)sender{
    if (sender.tag==1000) {
        /** 显示时间预览 */
        [sender setBackgroundImage:[UIImage imageNamed:@"timek"] forState:UIControlStateNormal];
        self.preview.hidden = NO;
        self.preview.isTime = YES;
        sender.tag=1001;
        return;
    }
    if (sender.tag==1001) {
        /** 显示桌面预览 */
        [sender setBackgroundImage:[UIImage imageNamed:@"fenlei"] forState:UIControlStateNormal];
        self.preview.hidden = NO;
        self.preview.isTime = NO;
        sender.tag=1002;
        return;
    }
    if (sender.tag==1002) {
        /** 取消预览 */
        [sender setBackgroundImage:[UIImage imageNamed:@"Detailtupian"] forState:UIControlStateNormal];
        self.preview.hidden = YES;
        sender.tag=1000;
        return;
    }
    
}

#pragma mark - 收藏视频
-(void)collectionButtonClick:(UIButton *)sender{
    self.collectionButton.selected = !self.collectionButton.selected;
    NSString *favor;
    if (self.collectionButton.selected==YES) {
        favor = @"1";
        [[LYVideoInfoManager share]addVideoToLocalData:self.model];
    }else{
        [[LYVideoInfoManager share]deleteVideoToLocalData:self.model];
        favor = @"2";
    }
    /** 发送通知 */
    NSDictionary *dic = @{@"isFavor":favor};
    [self postNotificationName:@"LYouUpdateFavorStater" object:self userInfo:dic];
}

#pragma mark - 来电显示
-(void)phoneShowButtonClick:(UIButton *)sender{
    LYShowCallController *showCallVC = [[LYShowCallController alloc]initThumbnail_url:self.model.thumbnail_url];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:showCallVC];
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - 下载壁纸
-(void)downLoadButtonClick:(UIButton *)sender{
    if (self.downLoadIng==YES) {
        /** 取消下载 */
        [[GDNetServerDownLoadTool sharedTool]stopAllDownLoadTasks];
        self.downLoadIng = NO;
        self.progress.hidden = YES;
        self.tipsLable.hidden = YES;
        return;
    }
    [UIView animateWithDuration:0.25
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^ {
                         self.downView.frame = CGRectMake(0, SCREEN_HEIGHT-150, SCREEN_WIDTH, 150);
                     }
                     completion:^(BOOL finished) {
                     }];
}

#pragma mark - 制作并保存LivePhoto到相册
-(void)makeLivePhototoSave{
    [LivePhotoMaker makeLivePhotoByLibrary:self.fileUrl completed:^(NSDictionary * resultDic) {
        if(resultDic) {
            NSURL * currenVideoUrl = resultDic[@"MOVPath"];
            NSURL * imageUrl = resultDic[@"JPGPath"];
            [LivePhotoMaker saveLivePhotoToAlbumWithMovPath:currenVideoUrl ImagePath:imageUrl completed:^(BOOL isSuccess) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.progress.hidden = YES;
                    self.tipsLable.hidden = YES;
                    /** 删除视频 */
                    [[GDNetServerDownLoadTool sharedTool]cancleLocalFile:self.filePath withUrlHost:self.model.video_url];
                    if(isSuccess) {
                        [EasyShowOptions sharedEasyShowOptions].textStatusType = ShowTextStatusTypeNavigation;
                        [EasyShowTextView showText:@"视频壁纸制作成功!"];
                    } else {
                        [EasyShowOptions sharedEasyShowOptions].textStatusType = ShowTextStatusTypeNavigation;
                        [EasyShowTextView showText:@"请先开启相册访问权限!"];
                    }
                });
            }];
        }
    }];
}

#pragma mark - 返回事件
-(void)backButtonClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc {
    [self.detailVideoView destoryPlayer];
}

@end
